package group.rober.common.service;

import group.rober.base.autoconfigure.RoberProperties;
import group.rober.common.entity.FileEntity;
import group.rober.saber.jdbc.accessor.DataAccessor;
import group.rober.saber.jdbc.accessor.impl.BeanDataAccessor;
import group.rober.saber.kit.FileKit;
import group.rober.saber.kit.IOKit;
import group.rober.saber.kit.MapKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileManageService {
    @Autowired
    private DataAccessor dataAccessor;
    @Autowired
    RoberProperties roberProperties;

    public DataAccessor getDataAccessor() {
        return dataAccessor;
    }

    public void setDataAccessor(DataAccessor dataAccessor) {
        this.dataAccessor = dataAccessor;
    }

    private String directory="/";

    public String getDirectory() {
        return directory;
    }

    public void setDirectory(String directory) {
        this.directory = directory;
    }

    public RoberProperties getRoberProperties() {
        return roberProperties;
    }

    public void setRoberProperties(RoberProperties roberProperties) {
        this.roberProperties = roberProperties;
    }

    protected String getFileRealPath(final String relativePath){
        String startPath = roberProperties.getFileStorageRoot()+directory;
        String endPath = relativePath;
        if(!startPath.endsWith("/"))startPath = startPath+"/";
        if(endPath.startsWith("/"))endPath = endPath.substring(1);
        return startPath + endPath;
    };

    public FileEntity saveFile(FileEntity fileEntity, InputStream inputStream) throws IOException {
        dataAccessor.save(fileEntity);

        String realPath = getFileRealPath(fileEntity.getStoredContent());
        File saveFile = new File(realPath);

        OutputStream outputStream = FileKit.openOutputStream(saveFile,true);
        IOKit.copy(inputStream,outputStream,4096);
        return fileEntity;
    }

    public FileEntity getFileEntity(String fileId){
        return dataAccessor.selectOne(FileEntity.class,"select * from COMO_FILE where ID=:id","id",fileId);
    }
    public void delete(String fileId){
        FileEntity fileEntity = getFileEntity(fileId);
        if(fileEntity == null)return;

        //找到文件并删除
        String realPath = getFileRealPath(fileEntity.getStoredContent());
        File file = new File(realPath);
        file.delete();
        //删除文件记录
        dataAccessor.delete(fileEntity);
    }

    public InputStream openInputStream(String fileId) throws IOException {
        FileEntity fileEntity = getFileEntity(fileId);
        if(fileEntity == null)return null;

        //找到文件并删除
        String realPath = getFileRealPath(fileEntity.getStoredContent());
        return FileKit.openInputStream(new File(realPath));
    }

}
